﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using AAPL.Common;
using AAPL.Common.DataShapes;
using AAPL.BAL.Services;

namespace WebUI.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(DateTime startDate, string sortBy, int? pageSize, int? pageIndex)
        {
            // get the data
            DateTime sunday = startDate.ToSunday();
            BlogService blogService = new BlogService();
            CategoryService categoryService = new CategoryService();
            DataPage<BlogPostSearchResult> page = blogService.GetPageOfBlogPostSearchResultsForWeek( sunday, pageSize.Value, pageIndex.Value, GetBlogPostSortOptionFromString(sortBy));
            List<CategoryWithPostCount> categoryList = categoryService.GetTopCategoryList(30);
            // Populate the viewdata
            ViewData["Posts"] = page ?? new DataPage<BlogPostSearchResult>();
            ViewData["ThisStartDate"] = sunday;
            ViewData["SortBy"] = sortBy;
            ViewData["PageSize"] = pageSize.Value;
            ViewData["PageIndex"] = pageIndex.Value;
            return View();
        }


        public ActionResult About()
        {
            return View();
        }


        private BlogService.BlogPostSortOption GetBlogPostSortOptionFromString(String sort)
        {
            switch (sort)
            {
                case "DATE":
                    return BlogService.BlogPostSortOption.ByDate;
                case "BLOGNAME":
                    return BlogService.BlogPostSortOption.ByBlogName;
                case "VOTE":
                    return BlogService.BlogPostSortOption.ByVote;
                default:
                    return BlogService.BlogPostSortOption.ByDate;
            }
        }
    }




    public static class ExtensionMethods
    {
        public static DateTime ToSunday(this DateTime date)
        {
            double offset = date.DayOfWeek == DayOfWeek.Sunday ? 0 : Convert.ToDouble(date.DayOfWeek);
            return date.AddDays(-offset);
        }

        public static List<Guid> ToGuidList(this string textList, char seperator)
        {
            var guidList = new List<Guid>();
            foreach (string guidText in textList.Split(seperator))
            {
                guidList.Add(new Guid(guidText));
            }
            return guidList;
        }
    }
}
